package com.xxx.springboot.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

/**
 * controller基类
 */
public abstract class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    public static final String USER_ID = "userId"; // 用户ID
    
    /**
     * 从request里获取用户ID
     */
    public String getUserIdFromRequest(HttpServletRequest request) {
        Object userId = request.getAttribute(USER_ID);
        if (userId == null) {
            logger.error("get userid from request fail");
            return null;
        }
        return (String) userId;
    }

    /**
     * 跳转404错误页面
     * 
     * @return ModelAndView 抛出视图
     */
    public ModelAndView errorView() {
        return new ModelAndView("/error/404.html");
    }

    /**
     * 跳转无权限访问错误页面
     * 
     * @return ModelAndView 抛出视图
     */
    public ModelAndView notAllowedView() {
        return new ModelAndView("/error/notAllow.html");
    }

    /**
     * 接收请求参数（不带密码）
     * 
     * @param request
     * @return
     */
    public String receivePost(HttpServletRequest request) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String reqBody = sb.toString();
         
            return URLDecoder.decode(reqBody, "UTF-8");
        } catch (Exception e) {
            logger.error("receivePost 发生异常," + e.getMessage(), e);
        }

        return "";
    }

}
